<template>
	<n-modal
		v-model:show="showModal"
		title="探店设置"
		preset="dialog"
		:show-icon="false"
		:mask-closable="false"
		style="width: 468px"
		@close="handleClose"
	>
		<div class="ll-modal-body">
			<div class="ll-list-item">
				<span class="ll-list-item-title">探店时间：</span>
				<div v-if="!tdSetDetail.startTime && !tdSetDetail.endTime">
					<n-date-picker
						v-model:value="range.dataTime"
						type="daterange"
						:is-date-disabled="disablePreviousDate"
						class="w-240px"
					/>
				</div>
				<div v-else-if="!changeTime">
					<span>
						{{
							tdSetDetail.startTime !== null && tdSetDetail.endTime !== null
								? `${tdSetDetail.startTime}～${tdSetDetail.endTime}`
								: '暂无'
						}}
					</span>
					<span class="ll-change" @click="() => (changeTime = true)">更改</span>
				</div>
				<div v-else>
					<n-date-picker
						v-model:value="range.dataTime"
						type="daterange"
						class="w-240px"
						:is-date-disabled="updateDisablePreviousDate"
					/>
				</div>
			</div>

			<div class="ll-list-item" style="align-items: normal">
				<span class="ll-list-item-title">探店模式：</span>
				<n-checkbox-group v-model:value="range.shopSeek">
					<n-space>
						<n-checkbox :value="1">到店</n-checkbox>
					</n-space>
				</n-checkbox-group>
				<n-checkbox-group v-model:value="range.cloudSeek">
					<n-space>
						<n-checkbox :value="1">云剪辑</n-checkbox>
					</n-space>
				</n-checkbox-group>
			</div>

			<template v-if="isShopSeek">
				<div class="ll-list-item">
					<span class="ll-list-item-title">探店名额：</span>
					<div v-if="!tdSetDetail.stock">
						<n-input-number
							v-model:value="range.stock"
							:show-button="false"
							placeholder="请输入探店主播份额"
							min="1"
							max="99999"
							:autosize="true"
							class="w-240px"
						>
							<template #suffix>份</template>
						</n-input-number>
					</div>

					<div v-else-if="!changeAllowed">
						<span>{{ tdSetDetail.stock !== null ? `${tdSetDetail.stock}份` : '暂无' }}</span>
						<span class="ll-change" @click="() => (changeAllowed = true)">更改</span>
					</div>

					<div v-else>
						<n-input-number
							v-model:value="range.stock"
							:show-button="false"
							placeholder="请输入探店主播份额"
							min="1"
							max="99999"
							:autosize="true"
							class="w-240px"
						>
							<template #suffix>份</template>
						</n-input-number>
					</div>
				</div>
			</template>

			<template v-if="(range.cloudSeek || []).includes(1)">
				<div class="ll-list-item">
					<span class="ll-list-item-title">云剪辑名额：</span>
					<div v-if="!tdSetDetail.cloudStock">
						<n-input-number
							v-model:value="range.cloudStock"
							:show-button="false"
							placeholder="请输入探店主播份额"
							min="1"
							max="99999"
							:autosize="true"
							class="w-240px"
						>
							<template #suffix>份</template>
						</n-input-number>
					</div>
					<div v-else-if="!isCloudClip">
						<span>
							{{ tdSetDetail.cloudStock !== null ? `${tdSetDetail.cloudStock}份` : '暂无' }}
						</span>
						<span class="ll-change" @click="() => (isCloudClip = true)">更改</span>
					</div>
					<div v-else>
						<n-input-number
							v-model:value="range.cloudStock"
							:show-button="false"
							placeholder="请输入云剪辑名额"
							min="1"
							max="99999"
							:autosize="true"
							class="w-240px"
						>
							<template #suffix>份</template>
						</n-input-number>
					</div>
				</div>
			</template>

			<div class="ll-list-item" style="align-items: normal">
				<span class="ll-list-item-title">佣金规则：</span>
				<n-checkbox-group v-model:value="range.commissionType">
					<n-space>
						<n-checkbox :value="3" disabled>CPS返佣</n-checkbox>

						<template v-if="isShopSeek">
							<n-checkbox :value="2">拍摄费</n-checkbox>
						</template>
					</n-space>
				</n-checkbox-group>
			</div>

			<div class="ll-list-item" style="align-items: normal">
				<span class="ll-list-item-hint">注：云剪辑固定佣金规则为CPS返佣</span>
			</div>

			<div class="ll-list-item" style="align-items: normal">
				<span class="ll-list-item-title">备注：</span>
				<n-input
					v-model:value="range.productRemark"
					type="textarea"
					maxlength="20"
					show-count
					style="width: 100%"
				/>
			</div>
		</div>

		<template #action>
			<n-button size="small" color="rgba(0, 0, 0, 0.1)" text-color="#333333" @click="handleClose">
				取消
			</n-button>
			<n-button type="primary" size="small" @click="handelConfirm">确定</n-button>
		</template>
	</n-modal>
</template>

<script setup>
import { ref, reactive, watch, computed } from 'vue';
import dayjs from 'dayjs';
// API接口
import { tdProductTdSetDetail, tdProductTdSetAdd } from '@/api/product';

import { useMessage } from 'naive-ui';

const message = useMessage();

const props = defineProps({
	modal: Boolean,
	productId: {
		type: Number,
		default: 0
	},
	commissionTypeStr: {
		type: String,
		default: ''
	}
});

const isShopSeek = computed(() => {
	const { shopSeek } = range;

	if (!shopSeek || !(shopSeek || []).includes(1)) {
		return false;
	}

	return true;
});

const emit = defineEmits(['update:modal', 'commit']);

const showModal = ref(props.modal);

watch(
	() => ({ ...props }),
	(count, prevCount) => {
		showModal.value = count.modal;
		if (count.modal) {
			resetData();
			handelReset();
			getTdProductTdSetDetail();
		}
	}
);

// 关闭弹框
const handleClose = () => {
	showModal.value = false;
	emit('update:modal', showModal.value);
	emit('commit');
};

const disablePreviousDate = (ts) => {
	return ts < new Date(new Date().toLocaleDateString()).getTime();
};

// 探店设置数据
const tdSetDetail = ref({
	startTime: null,
	endTime: null,
	stock: null,
	productRemark: null
});
let updateStartTime = 0;
// 获取设置详情
const getTdProductTdSetDetail = async () => {
	const setFrom = {
		productId: props.productId
	};

	const res = await tdProductTdSetDetail(setFrom);
	if (res.code === 200 && res.data !== null) {
		res.data.endTime = res.data.endTime ? dayjs(res.data.endTime).format('YYYY-MM-DD') : null;
		res.data.startTime = res.data.startTime ? dayjs(res.data.startTime).format('YYYY-MM-DD') : null;
		range.dataTime =
			res.data.startTime && res.data.endTime
				? [dayjs(res.data.startTime).valueOf(), dayjs(res.data.endTime).valueOf()]
				: null;
		res.data.stock = res.data.stock ? String(res.data.stock) : null;
		tdSetDetail.value = res.data;
		// 更新数据
		range.startTime = res.data.startTime
			? dayjs(res.data.startTime).format('YYYY-MM-DD HH:mm:ss')
			: null;
		range.endTime = res.data.endTime ? dayjs(res.data.endTime).format('YYYY-MM-DD HH:mm:ss') : null;
		range.stock = res.data.stock ? String(res.data.stock) : null;
		updateStartTime = res.data.startTime
			? new Date(dayjs(res.data.startTime).format('YYYY-MM-DD HH:mm:ss')).getTime()
			: 0;

		range.productRemark = res.data.productRemark;
		range.cloudSeek = [res.data.cloudSeek];
		range.shopSeek = [res.data.shopSeek];
		range.cloudStock = res.data.cloudStock;

		const commissionTypeRespList = res.data.commissionTypeRespList || [];
		range.commissionType = commissionTypeRespList.includes(3)
			? commissionTypeRespList
			: [3, ...commissionTypeRespList];
	}
};

const updateDisablePreviousDate = (ts) => {
	let date = new Date();
	return (
		ts < new Date(date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()).getTime()
	);
};

// 表单数据
const range = reactive({
	startTime: '',
	endTime: '',
	commissionType: [3],
	stock: null,
	dataTime: null,

	cloudSeek: null,
	shopSeek: null,

	cloudStock: null
});

watch(
	() => range.shopSeek,
	(count, prevCount) => {
		if (!count.includes(1)) {
			range.commissionType = [3];
		}
	}
);

// 重置数据
const resetData = () => {
	tdSetDetail.value = {
		startTime: null,
		endTime: null,
		commissionType: [3],
		stock: null
	};
	range.startTime = '';
	range.endTime = '';
	range.stock = null;
	range.dataTime = null;
	range.productRemark = null;
};

// 修改时间
const changeTime = ref(false);
// 修改名额
const changeAllowed = ref(false);
const handelReset = () => {
	changeTime.value = false;
	changeAllowed.value = false;

	isCloudClip.value = false;
};

// 修改云剪辑名额
const isCloudClip = ref(false);

const handelSetUp = async () => {
	if (!range.dataTime) {
		message.info('请选择探店时间！');
		return;
	}

	const isShopSeek = (range.shopSeek || []).includes(1);
	const isCloudSeek = (range.cloudSeek || []).includes(1);

	if (!isShopSeek && !isCloudSeek) {
		message.warning('请选择探店模式！');
		return;
	}

	if (isShopSeek && !range.stock) {
		message.warning('请输入探店名额！');
		return;
	}

	if (isCloudSeek && !range.cloudStock) {
		message.warning('请输入云剪辑名额名额！');
		return;
	}

	if (!range.commissionType || range.commissionType === '' || range.commissionType.length === 0) {
		message.info('请选择佣金类型！');
		return;
	}

	const setFrom = {
		startTime: dayjs(range.dataTime[0])
			.set('hour', 0)
			.set('minute', 0)
			.set('second', 0)
			.format('YYYY-MM-DD HH:mm:ss'),
		endTime: dayjs(range.dataTime[1])
			.set('hour', 23)
			.set('minute', 59)
			.set('second', 59)
			.format('YYYY-MM-DD HH:mm:ss'),

		cloudSeek: Number((range.cloudSeek || []).join('') || 0),
		shopSeek: Number((range.shopSeek || []).join('') || 0),

		productId: props.productId,
		commissionType: range.commissionType.join(','),
		productRemark: range.productRemark,

		stock: isShopSeek ? Number(range.stock) : 0,
		cloudStock: isCloudSeek ? Number(range.cloudStock) : 0
	};

	console.log(setFrom, 'setFrom');

	const res = await tdProductTdSetAdd(setFrom);
	if (res.code === 200) {
		message.success('设置成功！');
		handleClose();
	} else {
		message.warning(res.message);
	}
};

// 确定
const handelConfirm = async () => {
	handelSetUp();
};
</script>

<style lang="less" scoped>
.ll-list-item {
	min-height: 34px;
	font-size: 14px;
	color: #333333;
	display: flex;
	align-items: center;
	margin-bottom: 16px;

	&-hint {
		color: #f0944d;
	}

	&-title {
		color: #666666;
		display: inline-block;
		width: 86px;
		text-align: right;
	}
}

.ll-change {
	color: #1d6fe9;
	margin-left: 8px;
	cursor: pointer;
}
</style>
